package cn.wl.gulimall.auth.controller;

import cn.wl.common.constant.AuthServerConstant;
import cn.wl.common.exception.BizCodeEnume;
import cn.wl.common.utils.R;
import cn.wl.common.vo.MemberEntity;
import cn.wl.gulimall.auth.feign.MemberFeignService;
import cn.wl.gulimall.auth.feign.ThirdPartFeignService;
import cn.wl.gulimall.auth.vo.UserLoginVo;
import cn.wl.gulimall.auth.vo.UserRegistVo;
import com.alibaba.fastjson.TypeReference;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Controller
public class IndexController {
    @Autowired
    ThirdPartFeignService partFeignService;
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    MemberFeignService memberFeignService;

    @GetMapping("/sms/sendcode")
    @ResponseBody
    public R sendCode(@RequestParam("phone")String phone){
        //TODO 1.接口防刷
        String redisCode = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_PREFIX + phone);
        if(!StringUtils.isEmpty(redisCode)){
            long l = Long.parseLong(redisCode.split("_")[1]);
            if(System.currentTimeMillis()-l<60000){
                //60秒内不能再发
                return R.error(BizCodeEnume.SMS_CODE_EXCEPTION.getCode(),BizCodeEnume.SMS_CODE_EXCEPTION.getMsg());
            }
        }
        //2.验证码的再次校验,redis,寸存key-phone ,value -code  sms:code:
        String code = UUID.randomUUID().toString().substring(0, 5)+"_"+System.currentTimeMillis();
        //redis缓存验证码,防止同一个phone在60秒内再次发送验证码
        String s = code.split("_")[0];
        redisTemplate.opsForValue().set(AuthServerConstant.SMS_CODE_PREFIX+phone,code,10, TimeUnit.MINUTES);

        partFeignService.sendCode(phone,s);

        return R.ok();
    }

    /**
     * //TODO 重定向携带数据，利用session原理，将数据放在session中，只要跳到下一个页面取出这个数据后，session里面的数据就会删掉
     * //TODO 分布式下的session问题
     * @param vo
     * @param result
     * @param redirectAttributes
     * @return
     */
    @PostMapping("/regist")
    public String regist(@Valid UserRegistVo vo, BindingResult result, RedirectAttributes redirectAttributes){
        if(result.hasErrors()){
            Map<String,String> errors = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
//            model.addAttribute("errors",errors);
            redirectAttributes.addFlashAttribute("errors",errors);
            //校验出错
            return "redirect:http://auth.gulimall.com/reg.html";
        }

        //1.校验验证码
        String code = vo.getCode();
        String s = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_PREFIX + vo.getPhone());
        if(!StringUtils.isEmpty(s)){
            if(code.equals(s.split("_")[0])){
                //验证码通过
                //删除验证码
                redisTemplate.delete(AuthServerConstant.SMS_CODE_PREFIX + vo.getPhone());
                //真正注册，调用远程服务进行注册
                R regist = memberFeignService.regist(vo);
                if(regist.getCode()==0){
                    //成功
                    return "redirect:http://auth.gulimall.com/login.html";
                }else{
                    Map<String,String> map = new HashMap<>();
                    map.put("msg",regist.getData(new TypeReference<String>(){}));
                    redirectAttributes.addFlashAttribute("errors",map);
                    return "redirect:http://auth.gulimall.com/reg.html";
                }
            }else{
                Map<String,String> errors = new HashMap<>();
                errors.put("code","验证码错误");
//            model.addAttribute("errors",errors);
                redirectAttributes.addFlashAttribute("errors",errors);
                return "redirect:http://auth.gulimall.com/reg.html";
            }
        }else{
            Map<String,String> errors = new HashMap<>();
            errors.put("code","验证码错误");
//            model.addAttribute("errors",errors);
            redirectAttributes.addFlashAttribute("errors",errors);
            return "redirect:http://auth.gulimall.com/reg.html";
        }
    }
    @GetMapping("/login.html")
    public String loginPage(HttpSession session){
        Object attribute = session.getAttribute(AuthServerConstant.LOGIN_USER);
        if(attribute==null) {
            //没登录
            return "login";
        }else {
            return "redirect:http://gulimall.com";
        }


    }
    @PostMapping("/login")
    public String login(UserLoginVo vo, RedirectAttributes redirectAttributes, HttpSession session, HttpServletResponse response){
        //远程登录
        R login = memberFeignService.login(vo);
        if(login.getCode()==0){
            //成功
            //1.第一次使用session;命令浏览器保存卡号 jsessionid 这个cookie
            //以后浏览器访问哪个网站就会带上这个网站的cookie;
            //子域之间: gulimall.com  auth.gulimall.com order.gulimall.com
            //发卡的时候(指定域名为父域名)，即使是子域系统发的卡也能让父域直接使用
            MemberEntity member = login.getData("member", new TypeReference<MemberEntity>() {
            });
            //TODO 1.默认发的令牌。cookie作用域为当前作用域（解决子域session共享问题)
            //TODO 2.使用json的序列化方式来序列号对象数据到redis
            session.setAttribute(AuthServerConstant.LOGIN_USER,member);
//            new Cookie("JSESSIONID","111")
//            response.addCookie(new Cookie("JSESSIONID",));
            return "redirect:http://gulimall.com";
        }else{
            Map<String,String> errors = new HashMap<>();
            errors.put("msg",login.getData("msg",new TypeReference<String>(){}));
            redirectAttributes.addFlashAttribute("errors",errors);
            return "redirect:http://auth.gulimall.com/login.html";
        }
    }
}
